import React, { Fragment, PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { message } from 'antd';
import ListMenu from './ListMenu';
import drag_dir from '../../../../../../asserts/drag_dir.png';
import {
  ALL_FILE,
  COMMON_SUCCESS_STATE, DIRECTORIES,
  FILES,
  GARBAGE,
  QUICK_ACCESS
} from '../../../../../../constant';
import {
  fetchAllFileByParentId,
  fetchFileByCategoryId,
  listCategoryWithTree,
  updateMinCategoryChecked
} from '../../../../../../api';
import 'antd/lib/message/style';
import './index.less';
import { setCategory } from '../../../../../../redux/actions/category';
import { setFiles } from '../../../../../../redux/actions/files';
import { setLoading } from '../../../../../../redux/actions/loading';
import { toggleMenuListVisible } from '../../../../../../redux/actions/menuListVisible';


class PanHome extends PureComponent {

  static propTypes = {
    menuList: PropTypes.object,
    setCategory: PropTypes.func,
    folder: PropTypes.object,
    setFiles: PropTypes.func,
    setLoading: PropTypes.func,
    toggleMenuListVisible: PropTypes.func
  };

  state = {
    categories: [],
    activeCate: [1, 0] // 1 代表选中一级菜单的索引 (索引从一开始) 0 代表选中的二级菜单 (索引从一开始) 0代表不选中
  };

  // 默认选中的菜单项
  defaultLi = React.createRef()

  // 显示列表菜单
  showListMenu = async (event) => {
    const { toggleMenuListVisible } = this.props
    event.stopPropagation()
    // 显示菜单
    toggleMenuListVisible()
  };

  // 展开子菜单
  spreadNav = (event) => {
    event.preventDefault();
    const liNode = event.target.parentNode.parentNode.parentNode;
    let { className } = liNode;
    if (className.indexOf('spread') === -1) {
      className += ' spread';
    } else {
      className = className.replace(' spread', '');
    }
    liNode.className = className;
  };

  // 获取分类菜单数据
  listCategory = async () => {
    let {
      code,
      data
    } = await listCategoryWithTree();
    if (code === COMMON_SUCCESS_STATE) {
      // id 转为字符串防止数据
      this.setState({
        categories: data
      });
      // 设置分类学默认数据
      this.setupDefaultCategory(data)
    } else {
      message.error('请求分类数据异常');
    }
  };

  // 修改菜单子分类下的数据
  updateItem = (parentId, id, checked) => {
    const { categories } = this.state;
    // 使用map返回的数据，和原始数据地址不同
    let resultCategories = categories.map((item) => {
      if (item.id === parentId) {
        item.children.map((item1) => {
          if (id === item1.id) {
            item1.exist = checked;
          }
        });
      }
      return item;
    });
    this.setState({
      categories: resultCategories
    });
  };

  // 展示移出子菜单按钮
  showRemoveSubCateBtn = (parentId, id, event) => {
    // 保存当前点击的数据
    this.parentId = parentId;
    this.id = id;
    if (event.button === 2) {
      let x = event.clientX;
      let y = event.clientY;
      this.removeObject.style.left = x + 'px';
      this.removeObject.style.top = y + 'px';
      this.removeObject.style.display = 'block';
    }
  };

  // 移出子菜单点击删除子菜单
  removeSubMenu = async () => {
    let { parentId, id } = this
    let checked = false
    this.updateItem(parentId, id, checked)
    this.removeObject.style.display = 'none'
    let { code } = await updateMinCategoryChecked(id, checked)
    if (code !== COMMON_SUCCESS_STATE) {
      message.error('修改菜单数据异常')
    }
  }

  // 切换菜单选中样式
  clickMenu = (type, index, category, event) => {
    category['target'] = event.target
    // 添加当前点击实体至category,方便后续好调用菜单click方法，达到请求数据刷新效果
    // 修改点击选中菜单的样式
    const { activeCate } = this.state
    let resultActiveCate = activeCate.map((item, index1) => {
      item = 0
      if (type === index1) {
        item = index
      }
      return item
    })
    this.setState({
      activeCate: resultActiveCate
    })
    // 保存当前菜单项至redux中
    const { setCategory } = this.props
    setCategory(category)
    // 获取文件数据，通过菜单项
    this.fetchFileByCategory(category)
    event.stopPropagation()
  }

  // 设置redux默认分类数据
  setupDefaultCategory = (category) => {
    const { setCategory } = this.props
    // 设置默认选中元素
    category[0]['target'] = this.defaultLi.current
    setCategory(category[0])
    // 获取当前菜单下的分类数据
    this.fetchFileByCategory(category[0])
  }

  // 获取文件数据，通过菜单项
  fetchFileByCategory = async (category) => {
    const { folder, setFiles, setLoading } = this.props
    // 设置加载样式
    setLoading(true)
    let parentId = folder.id || 0
    let categoryId = category.id
    if (category.id === ALL_FILE) {
      // 获取我的文件
      let { data, code } = await fetchAllFileByParentId(parentId)
      if (code === COMMON_SUCCESS_STATE) {
        this.setFilesDefaultAttr(data)
        setFiles(data)
      } else {
        message.error('获取我的文件数据失败')
      }
    } else if (category.id === GARBAGE) {
      // 回收站
    } else if (category.id === QUICK_ACCESS) {
      // 快捷访问
    } else {
      // 其他文件分类获取
      // 获取我的文件
      let { data, code } = await fetchFileByCategoryId(categoryId)
      if (code === COMMON_SUCCESS_STATE) {
        this.setFilesDefaultAttr(data)
        setFiles(data)
      } else {
        message.error('获取我的文件数据失败')
      }
    }
    setLoading(false)
  }

  // 设置文件默认未选中样式
  setFilesDefaultAttr = (files) => {
    if (files[FILES]) {
      files[FILES].forEach((item) => {
        item.checked = false
        item.rename = false
        item.input = item.name
      })
    }
    if (files[DIRECTORIES]) {
      files[DIRECTORIES].forEach((item) => {
        item.checked = false
        item.rename = false
        item.input = item.name
      })
    }
  }

  componentDidMount () {
    this.listCategory();
  }

  render () {
    const {
      categories,
      activeCate
    } = this.state;
    return (
      <>
        <ul className="left_sub_nav_items">
          {
            categories.map((item, index) => {
              if (item.exist) {
                return (<Fragment key={item.id}>
                  <li ref={index === 0? this.defaultLi: null} onClick={(event) => this.clickMenu(0, index + 1, item, event)}
                    className={`left_sub_nav_item ${index === 0 ? 'spread active' : ''}`}>
                    <a className={activeCate[0] === (index + 1)? 'active': ''}>
                      <span>
                        {
                          item.children
                            ? <i className={`iconfont ${item.icon}`}
                              onClick={this.spreadNav}/>

                            : ''
                        }
                      </span>
                      {
                        item.name
                      }
                      {
                        item.children
                          ? <>
                            <i className="iconfont icon-cate-edit"
                              onClick={this.showListMenu}/>
                            <ListMenu className="subNavListMenu" item={item.children}
                              updateItem={(id, checked) => this.updateItem(item.id, id, checked)}/>
                          </>
                          : ''
                      }
                    </a>
                    {
                      item.children
                        ? <ul>
                          {
                            item.children.map((child, childIndex) => {
                              if (child.exist) {
                                return (
                                  <li onClick={(event) => this.clickMenu(1, childIndex + 1, child, event)}
                                    key={child.id} onMouseDown={(event) => this.showRemoveSubCateBtn(item.id, child.id, event)}>
                                    <a className={activeCate[1] === (childIndex + 1)? 'active': ''}>
                                      <i className={`iconfont ${child.icon}`}/>
                                      {
                                        child.name
                                      }
                                    </a>
                                  </li>
                                );
                              }
                            })
                          }
                          {/* 右键提示删除子菜单选项*/}
                          <div ref={(target) => this.removeObject = target}
                            className="remove-tip" onClick={this.removeSubMenu}>
                            <p>
                              从侧边栏移出
                            </p>
                          </div>
                        </ul>
                        : ''
                    }
                  </li>
                  {
                    index !== categories.length - 1 ? <span/> : ''
                  }
                </Fragment>);
              }
            })
          }
        </ul>
        {/* 拖入长用文件夹 */}
        <div className="drag_dir">
          <img src={drag_dir} alt=""/>
        </div>
        <div className="user_opacity">
          <div className="user_opacity_fore">
            <div className="user_opacity_back"/>
          </div>
          <div className="user_opacity_info">
            <span>
                517.6G/409G
            </span>
            <a href="/#">
              扩容
            </a>
          </div>
        </div>
      </>
    );
  }
}

export default connect(
  (state) => ({
    menuList: state.menuList,
    folder: state.folder
  }),
  {
    setCategory,
    setFiles,
    setLoading,
    toggleMenuListVisible
  },
)(PanHome);
